/**
 * @author Haidar Osman
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var conn=mongoose.createConnection('mongodb://localhost/UMLDB');
var member = new Schema({
	name : String
});
var classObject = new Schema({
	name : String,
	atts : [member],
	methods : [member]
});
var classShape = new Schema({
	classObj : [classObject],
	x : Number,
	y : Number
});
var relation = new Schema({
	from : String,
	to : String,
	title : String,
	type : String
});

var view = new Schema({
	name : String,
	classes : [classShape]
});

var model = new Schema({
	name : String,
	classes : [classObject],
	views : [view],
	relations : [relation]
});
var userSchema = new Schema({
	id : ObjectId,
	userName : String,
	password : String,
	models : {}//[model]
});

var User = conn.model('User', userSchema);
var incrementalId = 0;
// function findUserName()
exports.loadModels = function(req, res) {
	if(req.session.name) {
		var userName = req.session.name;
		
		User.where('userName', userName).run(function(err, docs) {
			
			if(docs.length > 0) {				
				res.contentType('json');
				res.json(docs[0].models);
			}
		});
	}
}
exports.getUserName = function(req, res) {
	if(req.session.name) {
		var JSON = {
			userName : req.session.name
		}
		res.contentType('json');
		res.json(JSON);
	} else {
		var JSON = {
			userName : "anonymous"
		}
		res.contentType('json');
		res.json(JSON);
	}
}
exports.saveModels = function(req, res) {
	if(req.session.name) {
		var userName = req.session.name;
		
		var i = 0;
		var models = req.body.models;
		
		User.where('userName', userName).run(function(err, docs) {
			if(docs.length > 0) {
				docs[0].models = req.body;
				docs[0].save();
			}
		});
		res.contentType('json');
		res.json(req.body);
	}
}
exports.registerNewUser = function(req, res) {
	var username = req.param("userName");	
	var count = 0;
	User.where('userName', username).run(function(err, docs) {
		count = docs.length;
		if(count == 0) {
			var user = new User();
			user.userName = req.param("userName");
			user.password = req.param("password");
			user.save();
			req.session.name = username;
			res.redirect("/index");
		} else {
			res.redirect("/loginUserForm");
		}
	});
}

exports.loginUser = function(req, res) {
	var userName = req.param("userName");
	var password = req.param("password");
	User.where('userName', userName).where('password', password).run(function(err, docs) {
		if(docs.length >= 1) {
			req.session.name = userName;
			res.redirect("/index");
		} else {
			res.redirect("/loginUserForm");
		}
	});
	
}
